#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "OLED.h"
#include "Motor.h"
#include "Encoder.h"
#include "temperature.h"
#include "LED.h"
#include "Key.h"
#include "BUZZER.h"
#include "Mytime.h"
//#include "tool.h"

enum state {
	OFF = 0,
	ON = 1
};

int16_t Speed_Encoder = 0;
int16_t Speed_Temp = 0;
uint16_t AD2 = 0;
uint8_t key_Swi = 0;
uint8_t key_Mode = 0;
uint8_t system_enabled = 0;

int main(void){

	OLED_Init();
	LED_Init();
	Key_Init();
	Motor_Init();
	Encoder_Init();
	Temp_Init();
	Buzzer_Init();
	MyRTC_Init();

	while(1){
		key_Swi =  Get_Switch_Num();
		if (key_Swi) {
			system_enabled = !system_enabled;
			if (system_enabled) {
				LED_switch(system_enabled);
				OLED_ShowString(1, 1, "Speed:0");
				OLED_ShowString(2, 1, "Mode:0");
				OLED_ShowString(3, 1, "Date:XXXX-XX-XX");
				OLED_ShowString(4, 1, "Time:XX:XX:XX");
			} else {
				LED_switch(system_enabled);
				Motor_Control(OFF);
				OLED_Clear();
			}
		}
		
		if (system_enabled) {
			//显示时间
			MyRTC_ReadTime();
			OLED_ShowNum(3, 6, MyRTC_Time[0], 4);		//显示MyRTC_Time数组中的时间值，年
			OLED_ShowNum(3, 11, MyRTC_Time[1], 2);		//月
			OLED_ShowNum(3, 14, MyRTC_Time[2], 2);		//日
			OLED_ShowNum(4, 6, MyRTC_Time[3], 2);		//时
			OLED_ShowNum(4, 9, MyRTC_Time[4], 2);		//分
			OLED_ShowNum(4, 12, MyRTC_Time[5], 2);		//秒
			
			//旋转编码器控制风扇
			key_Mode = Get_Mode_Num();
			OLED_ShowNum(2, 6, key_Mode, 1);
			if (key_Mode == 1) {
				Speed_Encoder += Get_Speed();
				OLED_ShowSignedNum(1, 7, Speed_Encoder, 3);
				Motor_Control(Speed_Encoder);
			}else if(key_Mode == 2) {
			//温度传感器控制风扇
				AD2 = Read_Temperature();
				Speed_Temp = 100 - (AD2 - 1700) * 100 / 360;
				OLED_ShowSignedNum(1, 7, Speed_Temp, 3);
				if (Speed_Temp < 30) Speed_Temp = 0;
				if (Speed_Temp > 70) {
					LED_buzzer(ON);
					Buzzer_switch(ON);
				}else {
					LED_buzzer(OFF);
					Buzzer_switch(OFF);
				}
							
				Motor_Control(Speed_Temp);
			}else {
				Motor_Control(OFF);
			}	
		}

	}
			
}
